package com.example.album;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import jakarta.servlet.http.HttpSession;

@Service
public class ImgManagementService {

    @Autowired
    private ImgRepository ir;
    @Value("${upload.dir:uploads}")
    private String uploadDir;
    public void uploadPhotos(String albumId, List<MultipartFile> photos, HttpSession session) {
        // 获取当前数据库图片总数
        long count = ir.count();
        String uploadId = null;
        if (session != null && session.getAttribute("userid") != null) {
            uploadId = session.getAttribute("userid").toString();
        }
        // 写入到可配置的外部目录，例如 {uploadDir}/img/{albumId}/
        File uploadRoot = new File(uploadDir);
        File targetDir = new File(uploadRoot, "img" + File.separator + albumId);
        String baseDir = targetDir.getAbsolutePath() + File.separator;
        File dir = targetDir;
        if (!dir.exists())
            dir.mkdirs();
        for (MultipartFile photo : photos) {
            count++;
            String originalName = photo.getOriginalFilename();
            String ext = "";
            int idx = originalName.lastIndexOf('.');
            if (idx >= 0)
                ext = originalName.substring(idx);
            String newFileName = count + ext;
            String filePath = baseDir + newFileName;
            try {
                photo.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
            Img img = new Img();
            img.setAlbumId(albumId);
            img.setPhotoId(String.valueOf(count));
            img.setUploadId(uploadId);
            img.setFileUrl("/img/" + albumId + "/" + newFileName);
            img.setStatus(0);
            ir.save(img);
        }
    }

    public void deletePhoto(String albumId, String photoId) {
        Img img = ir.findByPhotoId(photoId);
        if (img != null) {
            img.setStatus(1); // 假设1表示已删除
            ir.save(img);
        }
    }

}
